package com.example.myapplication.banner

import android.content.Context
import android.util.AttributeSet
import android.widget.VideoView

/**
 * 可缩放的VideoView，支持填满控件显示
 */
class ScalableVideoView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : VideoView(context, attrs, defStyleAttr) {

    private var videoWidth = 0
    private var videoHeight = 0

    /**
     * 设置视频尺寸
     */
    fun setVideoSize(width: Int, height: Int) {
        videoWidth = width
        videoHeight = height
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)

        if (videoWidth > 0 && videoHeight > 0) {
            // 计算缩放比例，选择较大的比例以确保填满控件
            val widthRatio = width.toFloat() / videoWidth.toFloat()
            val heightRatio = height.toFloat() / videoHeight.toFloat()
            val scaleRatio = widthRatio.coerceAtLeast(heightRatio)

            // 计算缩放后的尺寸
            val scaledWidth = (videoWidth * scaleRatio).toInt()
            val scaledHeight = (videoHeight * scaleRatio).toInt()

            // 居中显示
            setMeasuredDimension(scaledWidth, scaledHeight)
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        }
    }
}